package com.bw.gmall.realtime.dws.app;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.CartAddUuBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.DorisMapFunction;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.types.ListValue;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;

/**
 * @projectName: gmalll2206
 * @package: com.bw.gmall.realtime.dws.app
 * @className: DwsTradeCartAddUuWindow
 * @author: DuanYu
 * @description: TODO
 * @date: 2025/3/3 19:27
 * @version: 1.0
 */

public class DwsTradeCartAddUuWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeCartAddUuWindow().start(Constant.TOPIC_DWD_TRADE_CART_ADD, Constant.DWS_TRADE_CART_ADD_UU_WINDOW, 4, 10026);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        SingleOutputStreamOperator<JSONObject> etl = getEtl(dataStreamSource);
        SingleOutputStreamOperator<CartAddUuBean> keyByUserId = getKeyByUserId(etl);
        SingleOutputStreamOperator<CartAddUuBean> result = getProcess(keyByUserId);
        result.map(new DorisMapFunction<>()).sinkTo(FlinkSinkUtil.getDorisSink(Constant.DWS_TRADE_CART_ADD_UU_WINDOW));
    }

    private static SingleOutputStreamOperator<CartAddUuBean> getProcess(SingleOutputStreamOperator<CartAddUuBean> keyByUserId) {
        return keyByUserId.assignTimestampsAndWatermarks(WatermarkStrategy.<CartAddUuBean>forBoundedOutOfOrderness(Duration.ofSeconds(5)).withTimestampAssigner(new SerializableTimestampAssigner<CartAddUuBean>() {
            @Override
            public long extractTimestamp(CartAddUuBean cartAddUuBean, long l) {
                return cartAddUuBean.getTs();
            }
        })).windowAll(TumblingEventTimeWindows.of(Time.seconds(5))).process(new ProcessAllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
            @Override
            public void process(ProcessAllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>.Context context, Iterable<CartAddUuBean> iterable, Collector<CartAddUuBean> collector) throws Exception {
                ArrayList<CartAddUuBean> toList = ListUtil.toList(iterable);
                long carCt = toList.stream().mapToLong(e -> e.getCartAddUuCt()).sum();
                String start = DateFormatUtil.tsToDateTime(context.window().getStart());
                String end = DateFormatUtil.tsToDateTime(context.window().getEnd());
                String curDate = DateFormatUtil.tsToDate(System.currentTimeMillis());
                collector.collect(CartAddUuBean.builder()
                        .stt(start).edt(end).curDate(curDate).cartAddUuCt(carCt)
                        .build());
            }
        });
    }

    private static SingleOutputStreamOperator<CartAddUuBean> getKeyByUserId(SingleOutputStreamOperator<JSONObject> etl) {
        return etl.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getString("user_id");
            }
        }).process(new KeyedProcessFunction<String, JSONObject, CartAddUuBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("last_time", String.class);
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, CartAddUuBean>.Context context, Collector<CartAddUuBean> collector) throws Exception {
                long ts = jsonObject.getLong("ts") * 1000;
                String s = DateFormatUtil.tsToDateTime(ts);
                String value = valueState.value();
                Long cartAddUuCt = 0L;
                if (value == null && !s.equals(value)) {
                    cartAddUuCt = 1L;
                    valueState.update(s);
                }
                collector.collect(CartAddUuBean.builder().cartAddUuCt(cartAddUuCt).ts(ts).build());
            }
        });
    }


    private static SingleOutputStreamOperator<JSONObject> getEtl(DataStreamSource<String> dataStreamSource) {
        return dataStreamSource.flatMap(new RichFlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                if (s != null) {
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String id = jsonObject.getString("id");
                    if (id != null) {
                        collector.collect(jsonObject);
                    }
                }
            }
        });
    }

}